package com.dubbo.bootstrap;

import com.dubbo.utils.RuntimeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.File;

import static com.dubbo.StaticConstants.SLAVE_MARK_FILE;


public class Application {

    private static Logger logger = LoggerFactory.getLogger(Application.class);

    private int jettyPort;
    private String webapp;
    private String contentPath;
    private JettyServer jettyServer;
    private int nettyPort;
    private NettyServer nettyServer;

    public Application(int jettyPort, String webapp, String contentPath, int nettyPort) {
        this.jettyPort = jettyPort;
        this.webapp = webapp;
        this.contentPath = contentPath;
        this.nettyPort = nettyPort;
    }

    public static void bind(int jettyPort, String webapp, String contentPath, int nettyPort) throws Exception {
        RuntimeUtils.releasePort(jettyPort);
        RuntimeUtils.releasePort(nettyPort);

        Application application = new Application(jettyPort, webapp, contentPath, nettyPort);
        ApplicationHolder.set(application);
        application.start();
    }

    public static boolean isSlave() {
        File mark = new File(SLAVE_MARK_FILE);
        return mark.exists();
    }

    public void start() throws Exception {

        jettyServer = new JettyServer(jettyPort, webapp, contentPath);
        jettyServer.start();
        logger.info("Start Jetty Successfully");

        nettyServer = new NettyServer(nettyPort);
        nettyServer.start();
        logger.info("Start Netty Successfully");
    }




    public void stop() throws Exception {
        try {
            if (jettyServer != null) {
                jettyServer.stop();
                logger.info("Stop Jetty Successfully");
            }
        } finally {
            nettyServer.stop();
            logger.info("Stop Netty Successfully");
        }
    }
}
